package com.hongdee.crm.carConfig.service.impl;

import com.hongdee.crm.carConfig.dao.ITCrmCarWarrantyDao;
import com.hongdee.crm.carConfig.entity.TCrmCarWarranty;
import com.hongdee.crm.carConfig.service.ITCrmCarWarrantyService;
import com.hongdee.crm.task.dto.CarBrandDTO;
import com.hongdee.crm.task.dto.CarGuaranteedDTO;
import com.hongdee.crm.task.dto.CarSeriesDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by My on 2017/3/30.
 */
@Service
public class TCrmCarWarrantyServiceImpl implements ITCrmCarWarrantyService {

    private String tabName = "T_CRM_CAR_WARRANTY";

    @Autowired
    private ITCrmCarWarrantyDao crmCarWarrantyDao;

    private enum WARRANTYTYPE{
        GROUP,PARAM
    }

    /**
     * 方法名称: page
     * 方法描述: 分页查询品牌变更历史
     * 参数名称: String start 起始行数
     * 参数名称: String limit 分页大小
     * 参数名称: String sys_code 系统编码
     * 参数名称: String def_type 参数类型
     * 参数名称：String def_name 参数名称
     * 返回内容: Map
     * 异常说明: Exception
     * 创建用户:术洪超
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public Map page(String start, String limit, String pCode, String value) throws Exception {
        String sql = "select * from " + tabName + " where p_code = ?  ";
        List<Object> params = new ArrayList();
        params.add(pCode);
        if (!StringUtils.isEmpty(value)) {
            sql += " and ( code  like  ? or name like ? ) ";
            params.add("%" + value + "%");
            params.add("%" + value + "%");
        }
        return crmCarWarrantyDao.page(sql, params.toArray(), start, limit);
    }

    /**
     * 方法名称: info
     * 方法描述: 详情查询
     * 参数名称: String id 主键id
     * 返回内容: 实体对象
     * 异常说明: Exception
     * 创建用户:术洪超
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public Map info(String id) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(id)) {
            throw new Exception("请选择类型");
        }
        return this.crmCarWarrantyDao.info(tabName, "id", id);
    }


    /**
     * 方法名称: saveOrUpdate
     * 方法描述:  保存或更新实体，通过主键判断
     * 参数名称: ParamDef data 要保存的变更历史记录实体
     * 返回内容: ParamDef 保存后的历史记录实体
     * 异常说明: Exception
     * 创建用户:术洪超
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public TCrmCarWarranty saveOrUpdate(TCrmCarWarranty warranty) throws Exception {
        //判断参数是分组还是参数
        String type=String.valueOf(WARRANTYTYPE.GROUP.ordinal());
        boolean flag=false;
        if(warranty.getType().equals(type)){
            //分组 向上查询是否有重复
            if (exist(warranty.getCode(), warranty.getId())) {
                throw new Exception("该分类下已存在相同编码！");
            }
        }else{
            warranty.setDispOrder("999");
            //参数 当级别下是否有重复 排除自己
            flag=crmCarWarrantyDao.checkChild(warranty.getpCode(),warranty.getCode(),warranty.getId());
            if(!flag){
                throw new Exception("该分类下已存在相同编码！");
            }
        }
        this.crmCarWarrantyDao.saveOrUpdate(warranty);
        return warranty;
    }

    /**
     * 方法名称: update
     * 方法描述: 修改品牌状态
     * 参数名称: String id  主键id
     * 参数名称: String status 状态
     * 返回内容:
     * 异常说明:Exception
     * 创建用户:术洪超
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public void update(String id, String status) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择参数");
        }
        String hql = "update TCrmCarWarranty set status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.crmCarWarrantyDao.update(hql, params);
    }

    @Override
    public List tree(String pCode) throws Exception {
        return buildParamChild("-1", false);
    }


    /***
     * 查询任务定认参数值
     * @param pCode 默认为任务类型
     * @return
     */
    @Override
    public List treeParam(String pCode) throws Exception {
        return buildParamChild(pCode, true);
    }

//    /**
//     * 新增参数
//     * @param warranty
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public TCrmCarWarranty add(TCrmCarWarranty warranty) throws Exception {
//        return null;
//    }
//
//    /**
//     * 修改参数
//     * @param warranty
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public TCrmCarWarranty update(TCrmCarWarranty warranty) throws Exception {
//        //判断参数是分组还是参数
//        String type=String.valueOf(WARRANTYTYPE.GROUP.ordinal());
//        boolean flag=false;
//        if(warranty.getType().equals(type)){
//            //分组 向上查询是否有重复
//            if (exist(warranty.getCode(), warranty.getId())) {
//                throw new Exception("该分类下已存在相同编码！");
//            }
//        }else{
//            //参数 当级别下是否有重复 排除自己
//            flag=crmCarWarrantyDao.checkChild(warranty.getpCode(),warranty.getCode(),warranty.getId());
//            if(!flag){
//                throw new Exception("该分类下已存在相同编码！");
//            }
//        }
//        this.crmCarWarrantyDao.saveOrUpdate(warranty);
//        return warranty;
//    }


    /**
     * 树初始化
     * @param key
     * @param hasParam
     * @return
     * @throws Exception
     */
    private List buildParamChild(String key, boolean hasParam) throws Exception {
        //从缓存中取得用户已有的角色

        String sqlStr = " select * from "+tabName+" where p_code = ? and code not in (?)";
        if (!hasParam) {
            sqlStr += " and type != '1' ";
        }
        List<Map<String, Object>> treeP = this.crmCarWarrantyDao.childList(sqlStr, key);
        return buildParamParent(treeP, hasParam);
    }

    private List buildParamParent(List<Map<String, Object>> paramList, boolean hasParam) throws Exception {
        if (paramList.size() == 0) {
            return paramList;
        }
        List<Map<String, Object>> childList;
        for (Map map : paramList) {
            String resId = String.valueOf(map.get("code"));
            childList = buildParamChild(resId, hasParam);
            //存在子节点，增加子节点 返回
            map.put("child", childList);
        }
        return paramList;
    }

    /**
     * @param code 当前编码
     * @param id   主键
     * @return
     */
    private Boolean exist(String code, String id) throws Exception {
        String sql = "";
        List params = new ArrayList();
        if (null != id) {
            sql += "select 1 from " + tabName + " where code = ?  ";
            //更新时，增加主键判断
            sql += " and id != ? ";
            params.add(code);
            params.add(id);
        }else{
            sql += "SELECT * FROM "+tabName+" where p_code = ? ";
            params.add(code);
        }
        List ls = this.crmCarWarrantyDao.list(sql, params.toArray());
        return null != ls && ls.size() > 0;
    }



    /**
     * 获得质保参数信息
     * @return
     * @throws Exception
     */
    @Override
    public List<CarBrandDTO> findZbParamList(String code) throws Exception {
        TCrmCarWarranty carZbInfo=crmCarWarrantyDao.findCarZbInfo(code);
        if(carZbInfo!=null){
            List<CarBrandDTO> carBrandDTOList=new ArrayList<>();
            //获得车辆品牌信息
            List<TCrmCarWarranty> carLists=crmCarWarrantyDao.findParamByPCodeList(carZbInfo.getCode());
            if(carLists.size()>0){
                //遍历车辆品牌
                for (TCrmCarWarranty car:carLists) {
                    CarBrandDTO brandDTO=new CarBrandDTO();
                    brandDTO.setBrand(car.getName());
                    brandDTO.setCode(car.getCode());
                    //遍历车辆车系信息
                    List<CarSeriesDTO> carSeriesDTOS=this.findCarSeriesList(car);
                    brandDTO.setCarSeriesDTOS(carSeriesDTOS);
                    carBrandDTOList.add(brandDTO);
                }
            }
            return carBrandDTOList;
        }
        return null;
    }

    private List<CarSeriesDTO> findCarSeriesList(TCrmCarWarranty car) throws Exception {
        //根据品牌code 获得车系信息
        List<TCrmCarWarranty> carSeriesParamList=crmCarWarrantyDao.findParamByPCodeList(car.getCode());
        if(carSeriesParamList.size()>0) {
            List<CarSeriesDTO> carSeriesDTOS=new ArrayList<>();
            //
            Map<String,CarSeriesDTO> defSeriesMap=new HashMap<>();
            //遍历车系信息
            for (TCrmCarWarranty seariesParam : carSeriesParamList) {
                //判断是否有_下划线
                if(seariesParam.getCode().indexOf("_")!=-1){
                    String key=car.getCode();
                    CarSeriesDTO carSeriesDTO=null;
                    if(defSeriesMap.get(key)!=null){
                        carSeriesDTO=defSeriesMap.get(key);
                    }else{
                        carSeriesDTO=new CarSeriesDTO();
                        carSeriesDTO.setSeries(car.getName());
                        carSeriesDTO.setCode(car.getCode());
                    }
                    List<CarGuaranteedDTO> carGuaranteedDTOS = this.findCarGuaranteedInfos(car.getCode());
                    List<CarGuaranteedDTO> list=carSeriesDTO.getCarGuaranteedDTOS();
                    if(list!=null){
                        for (CarGuaranteedDTO dto:carGuaranteedDTOS) {
                            if(!list.contains(dto)){
                                list.add(dto);
                            }
                        }
                    }else{
                        list=carGuaranteedDTOS;
                    }
                    carSeriesDTO.setCarGuaranteedDTOS(list);
                    defSeriesMap.put(key,carSeriesDTO);
                }else {
                    CarSeriesDTO carSeriesDTO = new CarSeriesDTO();
                    carSeriesDTO.setSeries(seariesParam.getName());
                    carSeriesDTO.setCode(seariesParam.getCode());
                    //根据车系信息 获得其下的质保信息
                    List<CarGuaranteedDTO> carGuaranteedDTOS = this.findCarGuaranteedInfos(seariesParam.getCode());
                    //质保信息
                    carSeriesDTO.setCarGuaranteedDTOS(carGuaranteedDTOS);
                    carSeriesDTOS.add(carSeriesDTO);
                }
            }
            if(defSeriesMap.get(car.getCode())!=null){
                carSeriesDTOS.add(defSeriesMap.get(car.getCode()));
            }
            return carSeriesDTOS;
        }
        return null;
    }

    private enum WARRANTYINFO{
        year,mile,timePoint
    }

    private List<CarGuaranteedDTO> findCarGuaranteedInfos(String pCode) throws Exception {
        //获得质保信息
        List<TCrmCarWarranty> warrantyList=crmCarWarrantyDao.findParamByPCodeList(pCode);
        if(warrantyList.size()>0){
            List<CarGuaranteedDTO> carGuaranteedDTOList=new ArrayList<>();
            for (TCrmCarWarranty warranty:warrantyList) {
                CarGuaranteedDTO carGuaranteedDTO=this.caeateWarrantyParam(warranty);
                carGuaranteedDTOList.add(carGuaranteedDTO);

            }
            return carGuaranteedDTOList;
        }
        return null;
    }

    private CarGuaranteedDTO caeateWarrantyParam(TCrmCarWarranty warranty) throws Exception {
        CarGuaranteedDTO carGuaranteedDTO=new CarGuaranteedDTO();
        carGuaranteedDTO.setName(warranty.getName());
        carGuaranteedDTO.setCode(warranty.getCode());
        List<TCrmCarWarranty> paramList=crmCarWarrantyDao.findParamByPCodeList(warranty.getCode());
        if(paramList.size()>0) {
            for (TCrmCarWarranty param : paramList) {
                System.out.println(WARRANTYINFO.year.name());
                if(WARRANTYINFO.year.name().equals(param.getCode())){
                    carGuaranteedDTO.setYear(param.getDefValue());
                }
                if(WARRANTYINFO.mile.name().equals(param.getCode())){
                    carGuaranteedDTO.setMile(param.getDefValue());
                }
                if(WARRANTYINFO.timePoint.name().equals(param.getCode())){
                    carGuaranteedDTO.setTimePoint(param.getDefValue());
                }
            }
        }
        return carGuaranteedDTO;
    }


}
